# -*- coding: utf-8 -*-

from flask import Flask, request, jsonify, make_response
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import numpy as np
import base64
from io import BytesIO
import json
from PIL import Image
import time

app = Flask(__name__)
socketio = SocketIO()
socketio.init_app(app)
CORS(app)

# @app.before_request
# def before():
#     if request.method == 'OPTIONS':
#         print(request)
#         resp = make_response()
#         if 'ACCESS_CONTROL_REQUEST_HEADERS' in request.headers:
#             resp.headers['Access-Control-Allow-Headers'] = request.headers[
#                 'Access-Control-Allow-Headers']
#             resp.headers['Access-Control-Allow-Methods'] = request.headers[
#                 'Access-Control-Allow-Methods']
#             resp.headers['Access-Control-Allow-Origin'] = request.headers[
#                 'Origin']
#         return resp

# @app.after_request
# def after(resp):
#     print(resp)
#     if request.method != 'OPTIONS' and 'Origin' in request.headers:
#         resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
#     return resp


@app.route('/init')
def init():
    # TODO 初始化方法
    # init_parkings
    # init_cameras
    pass


@app.route('/ping')
def ping():
    print('ping')
    return jsonify({'status': 'ok'})


@socketio.on('video')
def send_test_data(data):
    data = json.loads(data)
    sid = request.sid
    print(sid)
    img_buffer = BytesIO()
    img = np.random.randint(0, 255, (300, 300)) * 255
    img = Image.fromarray(img.astype('uint8')).convert('L')
    img.save(img_buffer, format="JPEG")
    img_data = img_buffer.getvalue()
    b64img = base64.b64encode(img_data).decode('utf8')
    socketio.emit('video', json.dumps({'no': data.get('no'), 'frame': b64img}))


if __name__ == '__main__':
    socketio.run(app=app, host="0.0.0.0", port=9080, debug=True)
    # import cv2
    # img = np.random.randint(0, 255, (300, 300))
    # img *= 255

    # print(img)
    # cv2.imshow('test', img)
    # cv2.waitKey(0)